//
//  CommentWidget1.m
//  TodayComment
//
//  Created by 张吉阳 on 15/9/15.
//  Copyright (c) 2015年 xianrenmoshi. All rights reserved.
//

#import "CommentWidget.h"
#import "FxGetNews.h"
#import "FxBaseCell.h"
#import "DetailPage.h"
#import "ZCSHoldProgress.h"
#import "FxGetComment.h"
#import "AnimalCell.h"
#import "CommentCell.h"
#import "WMCommon.h"
#import "FxDBManager.h"
#import "FxDate.h"
#import "CommentMoreCell.h"
#import "UIColor+SNFoundation.h"
typedef enum state {
    kStateHome,
    kStateMenu
}state;

static const CGFloat viewSlideHorizonRatio = 0.75;
static const CGFloat viewHeightNarrowRatio = 0.80;
static const CGFloat menuStartNarrowRatio  = 0.70;

@interface CommentWidget()
@property (assign, nonatomic) state   sta;
@property (assign, nonatomic) CGFloat distance;
@property (assign, nonatomic) CGFloat leftDistance;
@property (assign, nonatomic) CGFloat menuCenterXStart;
@property (assign, nonatomic) CGFloat menuCenterXEnd;
@property (assign, nonatomic) CGFloat panStartX;

@property (strong, nonatomic) WMCommon               *common;
@end


@implementation CommentWidget
- (void)viewDidLoad
{
  self.cellIdentifier = @"CommentCell";
    _backCellIdentifier = @"MoreCommentCell";
    _cellHeight = 130;
    _hasNextPage = NO;
    _backHasNextPage = NO;
    _tableView.backgroundColor = [UIColor colorWithHexString:@"f0f0f0"];
    _backTableView.backgroundColor = [UIColor colorWithHexString:@"f0f0f0"];
    self.listDataPro = [[NSMutableArray alloc]init];
    self.listData = [[NSMutableArray alloc] init];
    self.backListData = [[NSMutableArray alloc] init];
    ////////////////////////////
   
    self.common = [WMCommon getInstance];
    self.sta = kStateHome;
    self.distance = 0;
    self.menuCenterXStart = self.common.screenW * menuStartNarrowRatio / 2.0;
    self.menuCenterXEnd = self.view.center.x;
    self.leftDistance = self.common.screenW * viewSlideHorizonRatio;
    
    
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
    pan.delegate =  self;
    [_tableView addGestureRecognizer:pan];
    UIPanGestureRecognizer *backPan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(backHandlePan:)];
    backPan.delegate =  self;
    [_backTableView addGestureRecognizer:backPan];
    if (refreshTableHeaderView == nil) {
        
        EGORefreshTableHeaderView *tableHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - _tableView.bounds.size.height, _tableView.frame.size.width, _tableView.bounds.size.height)];
        tableHeaderView.delegate = self;
        [_tableView addSubview:tableHeaderView];
        refreshTableHeaderView = tableHeaderView;
    }
    [self tableViewNight];
    [super viewDidLoad];
   
}
#pragma TableViewNight Method
- (void)tableViewNight
{
    _tableView.nightBackgroundColor = UIColorFromRGB(0x343434);
    _tableView.nightSeparatorColor = UIColorFromRGB(0x313131);
    _backTableView.nightBackgroundColor = UIColorFromRGB(0x343434);
    _backTableView.nightSeparatorColor = UIColorFromRGB(0x313131);
    self.navigationController.navigationBar.nightBarTintColor = UIColorFromRGB(0x343434);
    self.navigationController.navigationBar.nightTintColor = [UIColor darkGrayColor];

}

#pragma mark - NightMode Method;

- (void)nightFalls {
    [DKNightVersionManager nightFalling];
}

- (void)dawnComes {
    [DKNightVersionManager dawnComing];
}

#pragma mark - Refreth Methed

- (void)reloadTableViewDataSource
{
    [self.listData removeAllObjects];
    [self.listDataPro removeAllObjects];
    [self requestServerOp];
   reloading = YES;
}

- (void)doneLoadingTableViewData{
    
    //model should call this when its done loading
    reloading = NO;
    [refreshTableHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:_tableView];
    
}
#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if ([scrollView isEqual:_tableView]) {
        [refreshTableHeaderView egoRefreshScrollViewDidScroll:scrollView];
    }
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if ([scrollView isEqual:_tableView]) {
        [refreshTableHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
    }
    
}


#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
    
    [self reloadTableViewDataSource];
    [self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:3.0];
    
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
    
    return reloading; // should return if data source model is reloading
    
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
    
    return [NSDate date]; // should return date data source was last changed
    
}

#pragma mark - Pan Method
/**
 *  展示侧边栏
 */
- (void)showMenu {
    self.distance = self.leftDistance;
    self.sta = kStateMenu;
    [self doSlide:viewHeightNarrowRatio];
}

/**
 *  展示主界面
 */
- (void)showHome {
    self.distance = 0;
    self.sta = kStateHome;
    [self doSlide:1];
}

/**
 *  实施自动滑动
 *
 *  @param proportion 滑动比例
 */
- (void)doSlide:(CGFloat)proportion {
    [UIView animateWithDuration:0.3 animations:^{
       _tableView.center = CGPointMake(self.view.center.x + self.distance, self.view.center.y);
       _tableView.transform = CGAffineTransformScale(CGAffineTransformIdentity, proportion, proportion);

        
        CGFloat menuCenterX;
        CGFloat menuProportion;
        if (proportion == 1) {
            menuCenterX = self.menuCenterXStart;
            menuProportion = menuStartNarrowRatio;
        } else {
            menuCenterX = self.menuCenterXEnd;
            menuProportion = 1;
        }
    } completion:^(BOOL finished) {
        
    }];
}


/////////////////

#pragma ViewDidAppear Method

- (void)viewDidAppear:(BOOL)animated
{
    _tableView.nightBackgroundColor = UIColorFromRGB(0x343434);
    _tableView.nightSeparatorColor = UIColorFromRGB(0x313131);
    [super viewDidAppear:animated];
    
}


- (void)reloadData
{
    // 停止网络请求
    [_operation cancelOp];
    _operation = nil;
    
    // 先清除上次内容
    [self.listData removeAllObjects];
    [self.listDataPro removeAllObjects];
    [super reloadData];
}

- (BOOL)isReloadLocalData
{
    NSArray *array = [FxDBManager fetchChacheComments:self.columnInfo.ID];
    [self.listDataPro addObjectsFromArray:array];
    return [super isReloadLocalData];
}




#pragma mark - RequestNews Method
- (void)requestServerOp
{
    NSString *url = [NSString stringWithFormat:NewsURLFmt,
                     self.columnInfo.ID];
    
    NSDictionary *dictInfo = @{@"url":url};
    
    _operation = [[FxGetNews alloc] initWithDelegate:self opInfo:dictInfo];
    [_operation executeOp];
}

- (void)requestNextPageServerOp
{
    NSString *url = [NSString stringWithFormat:NextNewsURLFmt,
                     self.columnInfo.ID, (unsigned long)(self.listData.count - (self.listData.count)%10)];
    
    NSDictionary *dictInfo = @{@"url":url,
                               };
    
    _operation = [[FxGetNews alloc] initWithDelegate:self opInfo:dictInfo];
    [_operation executeOp];
}
- (void)opSuccess:(NSArray *)data
{
    if (data.count <= 0) {
        return;
    }
    else{
      _hasNextPage = YES;
      _operation = nil;
      [self.listData addObjectsFromArray:data];
      [self executeRealOpPro:data];
    }
}

- (void)opFail:(NSString *)errorMessage
{
    if ([errorMessage containsString:@"The Internet connection appears to be offline"]) {
        
        
        _hasNextPage = NO;
        
    }
    
}

- (void)executeRealOpPro:(NSArray *)array
{
    for (NewsInfo *info in array) {
        [self executeRealOp:info];
    }
}

#pragma OpSuccessEx  Method

- (void)opSuccessEx:(NSMutableArray *)data opinfo:(NSDictionary *)dictInfo
{
    [_operation cancelOp];
    _operation = nil;
    if (data.count <= 0) {
      //[self hideIndicator];
        _backHasNextPage = NO;
        return;
    }
    if([data count] >= 7){
        _backHasNextPage = YES;
        _backTableView.delegate = self;
        _backTableView.dataSource = self;
        [self.backListData addObjectsFromArray:data];
        [self updatePanUI];
        return;
    }
    else{
    NSDictionary *dictInfo = @{@"commentsid":[data[0] ID], @"date":[FxDate stringFromDateYMDHMS:[NSDate date]], @"chachecommentid": self.columnInfo.ID, @"json":[data[0] json]};
    [FxDBManager saveChacheComments:dictInfo];
        
     [self.listDataPro addObjectsFromArray:data];
     [self updateUI];
    }
}
- (void)opSuccessMatch:(id)data
{
    _count ++;
    [self executeNextRealOp];
    
}


- (void)updateUI
{
    
    [super updateUI];
    [self hideIndicator];
}

- (void)updatePanUI
{
    [_backTableView reloadData];
    [self hideIndicator];
}

#pragma mark - TableViewDelegat Method

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:_tableView]) {
        return indexPath.row < self.listDataPro.count ? _cellHeight:44;
    }
    else{
        return indexPath.row < self.backListData.count ? _cellHeight:44;

    }
    
}

- (CGFloat)p_HeightWithString:(NSString *)aString {
    CGRect r = [aString boundingRectWithSize:CGSizeMake(self.view.frame.size.width, 2000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:17.0f]} context:nil];
    return r.size.height;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([tableView isEqual:_tableView]) {
         return  _hasNextPage?self.listDataPro.count+1:self.listDataPro.count;
    }
    else{
         return  _backHasNextPage?self.backListData.count+1:self.backListData.count;
    }
  
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:_tableView]) {
        NSString *cellIdentifier = nil;
        BaseInfo *info = nil;
        
        if (indexPath.row < self.listDataPro.count) {
            cellIdentifier = self.cellIdentifier;
            info = [self.listDataPro objectAtIndex:indexPath.row];
        }
        else {
            cellIdentifier = @"CommentMoreCell";
            [self requestNextPageServerOp];
        }
        
        FxBaseCell *cell = (FxBaseCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        
        if (cell == nil) {
            NSArray* Objects = [[NSBundle mainBundle] loadNibNamed:cellIdentifier owner:tableView options:nil];
            cell = [Objects objectAtIndex:0];
            [cell initCell];
        }
        [cell setCellData:info];
        return cell;
    }
    else{
        NSString *cellIdentifier = nil;
            BaseInfo *info = nil;
        
            if (indexPath.row < self.backListData.count) {
                cellIdentifier = _backCellIdentifier;
                info = [self.backListData objectAtIndex:indexPath.row];
            }
            else {
                cellIdentifier = @"CommentMoreCell";
                [self executeNextOp];
            }
        
            FxBaseCell *cell = (FxBaseCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        cell.tag = 111111;
            if (cell == nil) {
                NSArray* Objects = [[NSBundle mainBundle] loadNibNamed:cellIdentifier owner:_backTableView options:nil];
                cell = [Objects objectAtIndex:0];
                [cell initCell];
            }
            [cell setCellData:info];
            return cell;
 
    }
        
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    FxBaseCell *cell = [tableView cellForRowAtIndexPath:indexPath];
      if ([cell.activityIndicatorView isAnimating]) {
             return;
          }
       if ([tableView isEqual:_backTableView]) {
        DetailPage *page = [[DetailPage alloc] init];
        page.commentInfo = [self.backListData   objectAtIndex:indexPath.row];
        UIViewController *owner =  self.owner;
        [owner.navigationController pushViewController:page animated:YES];
    }
    else{
        DetailPage *page = [[DetailPage alloc] init];
        page.commentInfo = [self.listDataPro objectAtIndex:indexPath.row];
        UIViewController *owner =  self.owner;
        [owner.navigationController pushViewController:page animated:YES];
    }
}




#pragma mark - UIPanGestureRecognizer method

- (void)handlePan:(UIPanGestureRecognizer *)recognizer {
     CGPoint point = [recognizer locationInView:_tableView ];
     NSIndexPath  *indexPath = [_tableView indexPathForRowAtPoint: point];
    FxBaseCell *cell = [_tableView cellForRowAtIndexPath:indexPath];
    if([cell.activityIndicatorView isAnimating]){
        return;
    }

       // 当滑动水平X大于75时禁止滑动
    if ([_backTableView isDragging]) {

    }
    if (recognizer.state == UIGestureRecognizerStateBegan) {
        [self.backListData removeAllObjects];
        self.panStartX = [recognizer locationInView:self.view].x;
    }
    if (self.sta == kStateHome && self.panStartX >= 75) {
        return;
    }
    
    CGFloat x = [recognizer translationInView:self.view].x;
    // 禁止在主界面的时候向左滑动
    if (self.sta == kStateHome && x < 0) {
        return;
    }
    
    CGFloat dis = self.distance + x;
    if (recognizer.state == UIGestureRecognizerStateChanged) {
        if (self.distance <= 0) {
        
        }
                 return;
    }    // 当手势停止时执行操作
    if (recognizer.state == UIGestureRecognizerStateEnded) {
        [self.backListData removeAllObjects];
        if (dis >= self.common.screenW * viewSlideHorizonRatio / 2.0) {
            [self executePanOp:[self.listDataPro objectAtIndex:indexPath.row]];
            [self showMenu];
        } else {
            [self.backListData removeAllObjects];
            [self showHome];
        }
        return;
    }
    
    CGFloat proportion = (viewHeightNarrowRatio - 1) * dis / self.leftDistance + 1;
    if (proportion < viewHeightNarrowRatio || proportion > 1) {
        return;
    }
    _tableView.center = CGPointMake(self.view.center.x + dis, self.view.center.y);
    _tableView.transform = CGAffineTransformScale(CGAffineTransformIdentity, proportion, proportion);

}

#pragma mark - backPanGestureRecognizer method
- (void)backHandlePan:(UIPanGestureRecognizer *)recognizer {
    
    // 当滑动水平X大于75时禁止滑动
    
    if (recognizer.state == UIGestureRecognizerStateBegan) {
        self.panStartX = [recognizer locationInView:self.view].x;
    }
    if (self.sta == kStateHome && self.panStartX >= 75) {
        return;
    }
    
    CGFloat x = [recognizer translationInView:self.view].x;
    // 禁止在主界面的时候向左滑动
    if (self.sta == kStateHome && x < 0) {
        
        return;
    }
    
    CGFloat dis = self.distance + x;
    if (recognizer.state == UIGestureRecognizerStateChanged) {
        return;
    }    // 当手势停止时执行操作
    if (recognizer.state == UIGestureRecognizerStateEnded) {
        if (dis >= self.common.screenW * viewSlideHorizonRatio / 2.0) {
            [self showMenu];
        } else {
            [self showHome];
        }
        return;
    }
    
    CGFloat proportion = (viewHeightNarrowRatio - 1) * dis / self.leftDistance + 1;
    if (proportion < viewHeightNarrowRatio || proportion > 1) {
        return;
    }
    _tableView.center = CGPointMake(self.view.center.x + dis, self.view.center.y);
    _tableView.transform = CGAffineTransformScale(CGAffineTransformIdentity, proportion, proportion);
    
}





#pragma mark - gestureRecognizerDelegat method

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    
    if ([otherGestureRecognizer.view isKindOfClass:[_tableView class]]) {
        
        return YES;
        
    }
        return NO;
    
}


- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if ([[touch.view class] isKindOfClass:[_tableView class]]) {
        return NO;
    }
    return  YES;
}


#pragma mark - UILongGestureRecognizer method

- (void)gestureRecogizerTarget:(UIGestureRecognizer *)gestureRecognizer
{
    if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {


    }
    if (gestureRecognizer.state == UIGestureRecognizerStateChanged) {

    }
    if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {
        
    }
    
    else if (gestureRecognizer.state == UIGestureRecognizerStatePossible) {
    }
}

#pragma executeRealOp  methed

- (void)executeRealOp:(NewsInfo *)info
{
    _boardid = info.name;
    _newsid = info.ID;
    NSString *url = [NSString stringWithFormat:CommentURLFmtAnimal, info.name, info.ID];
    NSDictionary *dictInfo = @{@"url":url,@"iconUrl":info.iconUrl, @"boardid":info.name, @"chacheCommentid":info.ID};
    
    _operation = [[FxGetComment alloc] initWithDelegate:self opInfo:dictInfo];
    [_operation executeOp];
}


- (void)executeNextRealOp
{
    NSString *url = [NSString stringWithFormat:NextCommentURLFmt, self.newsInfo.name, self.newsInfo.ID, (unsigned long)_count];
    
    NSDictionary *dictInfo = @{@"url":url,
                               };
    
    _operation = [[FxGetComment alloc] initWithDelegate:self opInfo:dictInfo];
    [_operation executeOp];
}

- (void)executeNextOp
{
    NSString *url = [NSString stringWithFormat:NextCommentURLFmt, _boardid, _newsid, (unsigned long)(self.backListData.count - (self.backListData.count)%10)];
    NSDictionary *dictInfo = @{@"url":url,
                               };
    
    _operation = [[FxGetComment alloc] initWithDelegate:self opInfo:dictInfo];
    [_operation executeOp];
}


#pragma executePanOp  methed
- (void)executePanOp:(CommentInfo *)info
{
    //http://comment.api.163.com/api/json/post/list/new/hot/news3_bbs/B562RS3B00014AEE_B5650DMB/0/10/10/2/2
     NSArray *array = [info.ID componentsSeparatedByString:@"_"];
    _boardid = info.boardid;
    _newsid = array[0];
    NSString *url = [NSString stringWithFormat:CommentURLFmt, info.boardid, array[0]];
    
    NSDictionary *dictInfo = @{@"url":url};
    
    _operation = [[FxGetComment alloc] initWithDelegate:self opInfo:dictInfo];
    [_operation executeOp];
}

- (void)updateAnimalUI:(NSArray *)data
{
    CGFloat x = CGRectGetMinX(_holdProgress.progressView.frame);
    CGFloat y = CGRectGetMinY(_holdProgress.progressView.frame);
    for (CommentInfo  *info in data) {
        NSArray *object = [[NSBundle mainBundle]loadNibNamed:@"AnimalCell" owner:_holdProgress.progressView options:nil];
        AnimalCell *cell = [object objectAtIndex:0];
        [cell initCell];
        [cell setCellData:info];
        cell.frame = CGRectMake(x ,y , 320, 130);
        [_holdProgress.progressView addSubview:cell];
        [_holdProgress.progressView bringSubviewToFront:cell];
        y = y + 130;
    }
}


@end
